using System;
using System.Collections.Generic;
using System.Text;
using System.Resources;
using System.Reflection;
using System.Web;
using System.IO;
using System.Net;
using System.Drawing.Imaging;
using System.Drawing;

namespace JumploaderWrapper
{
  public class ResourceHandler : IHttpHandler
  {
    private HttpRequest _request;
    private HttpResponse _response;

    #region IHttpHandler Members

    public bool IsReusable
    {
      get { return false; }
    }

    public void ProcessRequest(HttpContext context)
    {
      _request = context.Request;
      _response = context.Response;

      string name = _request.QueryString["Resource"];
      string type = _request.QueryString["Type"];
      if ((name == null) || (type == null))
      {
        if (context.Cache["Name"] != null)
        {
          name = context.Cache["Name"].ToString();
          type = context.Cache["Type"].ToString();
        }
        else
        {
          throw new ArgumentException("To use this handler you must specify the resource to retrieve");
        }
      }

      context.Cache["Name"] = name;
      context.Cache["Type"] = type;

      _response.Clear();

          switch (type)
          {
            case "applet":
              byte[] data = LoadItem(name);
              WriteApplet(data, name);
              break;
            case "jpg":
            case "jpeg":
              WriteImage(name, type, ImageFormat.Jpeg);
              break;
            case "gif":
              WriteImage(name, type, ImageFormat.Gif);
              break;
            case "png":
              WriteImage(name, type, ImageFormat.Png);
              break;
            default:
              throw new ArgumentException("Invalid Resource Type Specified.");
          }

      return;
    }

    protected void WriteApplet(byte[] binary, string name)
    {
        if (binary == null)
            return;

      _response.ContentType = "application/octet-stream";
      _response.AddHeader("ContentLength", binary.Length.ToString());
      _response.BinaryWrite(binary);
      _response.Flush();
    }

    protected void WriteImage(string name, string type, ImageFormat format)
    {
        _response.ContentType = "image/" + type;
        Bitmap imageData = (Bitmap)Properties.Resources.ResourceManager.GetObject(name);
        MemoryStream ms = new MemoryStream();
        imageData.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
        ms.WriteTo(_response.OutputStream);

        imageData.Dispose();
        ms.Close();
    }

    protected byte[] LoadItem(string name)
    {
      return (byte[])Properties.Resources.ResourceManager.GetObject(name);
        
    }

    #endregion
  }
}
